<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="50">
        <el-col :span="10">
          <el-input placeholder="请输入内容" clearable @clear="getUser" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="success" @click="addDialogVisible=true">增加用户</el-button>
        </el-col>
      </el-row>

      <el-table class="margin-top1" :data="getUserList" border style="width: 100%">
        <el-table-column fixed prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="120"></el-table-column>
        <el-table-column prop="mobile" label="mobile" width="120"></el-table-column>
        <el-table-column prop="role_name" label="用户信息" width="120"></el-table-column>
        <el-table-column prop="mg_state" label="管理用户" width="300">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="isUserModule(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="delUser(scope.row)" icon="el-icon-delete"></el-button>
            <el-button
              type="warning"
              icon="el-icon-edit"
              size="mini"
              @click="ediUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              :enterable="false"
              placement="top"
            >
              <el-button
                type="primary"
                size="mini"
                @click="ggUser(scope.row)"
                icon="el-icon-star-off"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="margin-top1"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 增加用户对话框 -->
    <el-dialog title="增加用户" :visible.sync="addDialogVisible" width="50%" @close="addrest">
      <el-form :model="addForm" :rules="addRules" ref="addruleFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkpassword">
          <el-input v-model="addForm.checkpassword"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editeDialogVisible" width="50%" @close="editerest">
      <el-form :model="addForm" :rules="addRules" ref="editeruleFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editeUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="rightsDialogVisible" width="50%" @close='rightclose'>
      <p>用户名:{{getrightlist.username}}</p>
      <p>角色信息:{{getrightlist.role_name}}</p>
      <span>修改角色：</span>
      <el-select v-model="select" placeholder="请选择">
        <el-option v-for="item in options" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightsUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getUser();
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value !== this.addForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      var emailreg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (emailreg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确邮箱!"));
      }
    };
    var validateMobile = (rule, value, callback) => {
      var mobilereg = /^1[345789]\d{9}$/;
      if (mobilereg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确手机号!"));
      }
    };
    return {
      getUserList: [],
      getrightlist: {
        id: 0,
        username: "",
        role_name: ""
      },
      options: [],
      select: "",
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      total: 0,
      addDialogVisible: false,
      editeDialogVisible: false,
      rightsDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        checkpassword: "",
        email: "",
        mobile: ""
      },
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
        ],
        checkpassword: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    async getUser() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getUserList = res.data.users;
      this.total = res.data.total;
    },
    async isUserModule(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    addUser() {
      this.$refs.addruleFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.addDialogVisible = false;
        this.getUser();
      });
    },
    // 增加对话框关闭时
    addrest() {
      this.$refs.addruleFormRef.resetFields();
    },
    // 增加对话框关闭时
    editerest() {
      this.addForm = {
        username: "",
        password: "",
        checkpassword: "",
        email: "",
        mobile: ""
      };
    },
    async delUser(info) {
      let del = await this.$confirm(
        `此操作将永久删除该${info.username}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (del !== "confirm") return this.$message.info("取消了删除");
      const { data: res } = await this.$http.delete("users/" + info.id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUser();
    },
    async ediUser(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.addForm = res.data;
      this.editeDialogVisible = true;
    },
    editeUser() {
      this.$refs.editeruleFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.addForm.id,
          this.addForm
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.editeDialogVisible = false;
        this.getUser();
      });
    },
    // 分配角色
    async ggUser(info) {
      this.getrightlist.id = info.id;
      this.getrightlist.username = info.username;
      this.getrightlist.role_name = info.role_name;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.options = res.data;
      this.rightsDialogVisible = true;
    },
    rightclose(){
      this.select=''
    },
    // 修改角色
    async rightsUser() {
      const {
        data: res
      } = await this.$http.put(`users/${this.getrightlist.id}/role`, {
        rid: this.select
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rightsDialogVisible = false;
      this.getUser();
      this.$message.success(res.meta.msg);
    },
    handleSizeChange(newpage) {
      this.queryInfo.pagesize = newpage;
      this.getUser();
    },
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage;
      this.getUser();
    }
  }
};
</script>
<style lang="less" scoped>
</style>